package T11_new_lock_read_and_write;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class T10_new_lock_read_and_write {    
    public static void main(String[] args) {    
        MyCount myCount = new MyCount("95599200901215522", 10000);    
        ReadWriteLock lock = new ReentrantReadWriteLock(false);    
        ExecutorService pool = Executors.newFixedThreadPool(2);    
        User u1 = new User("lang1", myCount, -4000,lock, false);    
        User u2 = new User("lang2", myCount, 6000, lock, false);    
        User u3 = new User("lang3", myCount, -8000,lock, false);    
        User u4 = new User("lang4", myCount, 800, lock, false);   
        User u5 = new User("lang4", myCount, 800, lock, true);
        pool.execute(u1);    
        pool.execute(u2);    
        pool.execute(u3);    
        pool.execute(u4);    
        pool.execute(u5);    
        pool.shutdown();    
    }    
}    
    
class User implements Runnable {    
	private String name;                
	private MyCount myCount;       
	private int iocash;                 
	private ReadWriteLock myLock;               
	private boolean ischeck;       
	User(String name, MyCount myCount, int iocash, ReadWriteLock myLock, boolean ischeck) {    
        this.name = name;    
        this.myCount = myCount;    
        this.iocash = iocash;    
        this.myLock = myLock;    
        this.ischeck = ischeck;    
	}    
	public void run() {    
		if (ischeck) {   
			myLock.readLock().lock();    
			System.out.println("读：" + name + "正在查询" + myCount 
					+ "账户，当前金额为" + myCount.getCash());    
			myLock.readLock().unlock();    
        } else {    
        	myLock.writeLock().lock();    
        	System.out.println("写：" + name + "正在操作" + myCount 
        			+ "账户，金额为         " + iocash + "，当前金额为" + myCount.getCash());    
        	myCount.setCash(myCount.getCash() + iocash);    
        	System.out.println("写：" + name + "操作          " + myCount 
        			+ "账户成功，金额为" + iocash + "，当前金额为" + myCount.getCash());    
        	myLock.writeLock().unlock();    
        }    
	}    
}      
class MyCount {    
	private String oid;        
	private int cash;            
	MyCount(String oid, int cash) {    
        this.oid = oid;    
        this.cash = cash;    
	}    
	public String getOid() {    
        return oid;    
	}    
	public void setOid(String oid) {    
        this.oid = oid;    
	}    
	public int getCash() {    
        return cash;    
	}    
	public void setCash(int cash) {    
        this.cash = cash;    
	}    
	@Override    
	public String toString() {    
        return "MyCount{" +"oid='" + oid + '\'' + ", cash=" + cash + '}';    
	}    
}  
